var express = require('express');
var router = express.Router();
const md5 = require('md5');
const user = require('../sql/User')

router.get('/', function(req, res, next) {
  
  const { employeesName } = req.session.userData;
  res.render('setPassword', { employeesName, index:0 });
  
});

// 修改个人密码
router.post('/set', function(req, res, next) {
  const uId = req.session.userData.uId;
  const { opw, npw } = req.body;
  user.find({uId, password: md5(opw)}).then((userData)=>{
    if(userData < 1){
      req.flash('error', '旧密码不对');
      res.redirect('/setpassword');
    }else{
      user.updateOne({ uId, password: md5(opw) }, { password: md5(npw) }).then(()=>{
        req.session.userData = {};
        res.redirect('/login');
      }).catch(code=>{
        res.redirect('/setpassword');
        console.error(code);
      })
    }
  }).catch(code=>{
    res.redirect('/setpassword');
    console.error(code);
  })
});

module.exports = router;
